﻿namespace MsForgeReboot.Web.Areas.ControlPanel.Controllers {
    #region Usings

    using System;
    using System.Web.Mvc;
    using AutoMapper;
    using MsForgeReboot.Framework.Entities;
    using MsForgeReboot.Framework.Extensions;
    using MsForgeReboot.Framework.Interfaces;
    using MsForgeReboot.Framework.ViewModels;
    using MsForgeReboot.Web.Attributes;

    #endregion

    public class UserGroupController : Controller {
        private readonly IUserGroupService userGroupService;

        public UserGroupController(IUserGroupService userGroupService) {
            this.userGroupService = userGroupService;
        }

        public ActionResult Index(int page = 1, int pageSize = 10) {
            return this.View(this.userGroupService.GetList(page, pageSize));
        }

        public ActionResult Create() {
            this.ViewBag.Title = "Registruj novu korisničku grupu";
            return this.View("Edit", new UserGroupEditModel());
        }

        [HttpPost]
        [IgnorePropertyValidation("Author.PublicName", "Author.UserName")]
        public ActionResult Edit(UserGroupEditModel model) {

            if (this.ModelState.IsValid) {
                var userGroup = Mapper.Map<UserGroup>(model);

                userGroup.Published = DateTime.Now;
                userGroup.UrlPointer = model.Title.GetUrlFriendlyText();

                this.userGroupService.Save(userGroup);
                return this.RedirectToAction("Index");
            }

            return this.View("Edit", model);

        }

        [HttpPost]
        public ActionResult Delete(string urlPointer) {
            this.userGroupService.Delete(urlPointer);
            return this.Json("success", JsonRequestBehavior.DenyGet);
        }

        public ActionResult Edit(string urlPointer) {
            var userGroup = this.userGroupService.GetByUrlPointer(urlPointer);

            if (userGroup == null) {
                return this.HttpNotFound();
            }

            var model = new UserGroupEditModel { Id = userGroup.Id, Title = userGroup.Title, Body = userGroup.Body, Author = Mapper.Map<UserViewModel>(userGroup.Author) };

            return this.View("Edit", model);
        }
    }
}
